package com.mifengkong.kotlincommon.indicator

import android.content.Context
import android.content.res.TypedArray
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.View
import android.widget.HorizontalScrollView
import com.mifengkong.kotlincommon.R

/**
 * Created by jack on 2018/5/31
 */
class TrackIndicatorView : HorizontalScrollView, ViewPager.OnPageChangeListener {

    private lateinit var mAdapter: IndicatorAdapter
    private var mIndicatorGroup: IndicatorViewGroup
    private var mViewPager: ViewPager? = null
    private var mItemWidth: Int = 0   //单个item的宽度
    private var mCurrentPosition = 0
    private var mVisibleItemNum: Int
    private var mIsExecuteScroll: Boolean = false
    private var mOnPageChangeListener: OnPageChangeListener? = null

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        mIndicatorGroup = IndicatorViewGroup(context)
        val array: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.TrackIndicatorView)
        mVisibleItemNum = array.getInteger(R.styleable.TrackIndicatorView_tabVisibleNum, 4)
        array.recycle()
        addView(mIndicatorGroup)
    }

    fun setAdapter(adapter: IndicatorAdapter?) {
        mAdapter = adapter!!
        val itemCount = mAdapter.getItemCount()
        for (i in 0 until itemCount) {
            val itemView: View = mAdapter.getView(i, mIndicatorGroup)
            mIndicatorGroup.addItemView(itemView)
            if (null != mViewPager) {
                switchItemViewClick(itemView, i)
            }
        }
        mAdapter.highLightIndicator(mIndicatorGroup.getItemViewAt(0))
    }

    fun setAdapter(adapter: IndicatorAdapter?, viewPager: ViewPager?) {
        mViewPager = viewPager
        mViewPager?.addOnPageChangeListener(this)
        setAdapter(adapter)
    }

    private fun switchItemViewClick(itemView: View, position: Int) {
        itemView.setOnClickListener {
            mViewPager?.setCurrentItem(position, false)
            mOnPageChangeListener?.selected(position)
            scrollCurrentIndicator(position, 0f)
            mIndicatorGroup.scrollBottomTrackView(position)
        }
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        if (changed) {
            mItemWidth = getItemWidth()
            for (i in 0 until mAdapter.getItemCount()) {
                mIndicatorGroup.getItemViewAt(i).layoutParams.width = mItemWidth
            }
            mIndicatorGroup.requestViewLayout()
            mIndicatorGroup.setBottomTrackView(mAdapter.getBottomTrackView(), mItemWidth)
        }
    }

    /**
     * 计算单个item的宽度（有可能每个item的宽度都是不一样的，这时候我们需要取最大的那个）
     */
    private fun getItemWidth(): Int {
        val parentWidth = width
        if (mVisibleItemNum > 0) {
            return parentWidth / mVisibleItemNum
        }
        var itemWidth: Int
        var maxItemWidth = 0
        for (i in 0 until mAdapter.getItemCount()) {
            val currentItemWidth = mIndicatorGroup.getItemViewAt(i).width
            maxItemWidth = Math.max(currentItemWidth, maxItemWidth)
        }
        itemWidth = maxItemWidth
        val allItemWidth = itemWidth * mAdapter.getItemCount()
        if (allItemWidth < parentWidth) {
            itemWidth = parentWidth / mAdapter.getItemCount();
        }
        return itemWidth
    }

    override fun onPageScrollStateChanged(state: Int) {
        if (state == 0) {
            mIsExecuteScroll = false
        } else if (state == 1) {
            mIsExecuteScroll = true
        }
    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
        if (mIsExecuteScroll) {
            //滚动的时候调用
            scrollCurrentIndicator(position, positionOffset)
            mIndicatorGroup.scrollBottomTrackView(position, positionOffset)
        }
    }

    /**
     * 不断滚动当前指示器，让当前指示器居中（和ViewPager联动）
     */
    private fun scrollCurrentIndicator(position: Int, positionOffset: Float) {
        val totalScroll = (position + positionOffset) * mItemWidth   //总的长度
        val leftScroll = (width - mItemWidth) / 2   //滚动左边的长度
        val finalScroll = totalScroll - leftScroll   //最终需要滚动的长度
        if (positionOffset == 0f) {
            smoothScrollTo(finalScroll.toInt(), 0)
        } else {
            scrollTo(finalScroll.toInt(), 0)
        }
    }

    fun setOnPageChangeListener(onPageChangeListener: OnPageChangeListener) {
        mOnPageChangeListener = onPageChangeListener
    }

    override fun onPageSelected(position: Int) {
        mAdapter.resetIndicator(mIndicatorGroup.getItemViewAt(mCurrentPosition))
        mCurrentPosition = position
        mOnPageChangeListener?.selected(mCurrentPosition)
        mAdapter.highLightIndicator(mIndicatorGroup.getItemViewAt(mCurrentPosition))
    }

    fun setTabVisibleNum(visibleItemNum: Int) {
        mVisibleItemNum = visibleItemNum
    }

    interface OnPageChangeListener {
        fun selected(position: Int)
    }
}